Previous | Next | Trail Map | Creating a User Interface | Anatomy of a Program with a Graphical UI


Event Handling

When the user acts on a Component -- clicking it or pressing the Return key, for example -- an Event object is created. The AWT event-handling system passes the Event up the Component hierarchy until one of the Components handles it.

It's possible for more than one Component to handle a single event. For example, in the example program when the user presses Return in a text field, the associated TextField object partially handles the event (setting the TextField value??). It then allows the TextField's Container to see the event. The Container reacts to the event by updating the slider below the text field. The Container then tells the event-handling system that the event has been completely handled -- that its own Container (a ConversionPanel) shouldn't be passed the event.

The Event Object

Each event results in the creation of an Event object. Each Event object includes the following information:

How to Implement an Event Handler

Components can respond to events by implementing the handleEvent() method or by implementing a method that's specific to one type of event. The latter works because the default (Component) definition of the handleEvent() method simply calls a method that's specific to the event type. These event-specific methods are mouseEnter(), mouseExit(), mouseMove(), mouseUp(), mouseDown(), mouseDrag(), keyDown(), and action().

In the example program, all the event handling is performed by ConversionPanels. They use the handleEvent() method to catch events resulting from user actions on the slider (Scrollbar), text field (TextField), and pop-up list (Choice).

Here is the ConversionPanel implementation of the handleEvent method:

public boolean handleEvent(Event e) {
    if (e.target instanceof Scrollbar) {
        textField.setText(String.valueOf(slider.getValue()));
        controller.convert(this);
        return true;
    } else if (e.target instanceof TextField) {
        setSliderValue(getValue());
        controller.convert(this);
        return true;
    } else if (e.target instanceof Choice) {
        controller.convert(this);
        return true;
    }
    return false;
}
The method simply makes sure that the ConversionPanel's slider and text field both show the same value, and then asks the Converter object to update the other ConversionPanel. If the event target isn't a Scrolbar, TextField, or Choice, the method returns false, indicating that it couldn't handle the event and that the event should be passed up the Component hierarchy. Otherwise, the method returns true, indicating that the event has been completely handled.


Previous | Next | Trail Map | Creating a User Interface | Anatomy of a Program with a Graphical UI